<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/


defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

class JobBoardModelJAPermissions extends JModel
{
	
	var $_data;
    var $_table;
    var $_pagination;
    
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    function getItems($group, $usergroup, $usertype){
    	global $mainframe;    	    	
    	
    	$db = &JFactory::getDBO();
    	
    	$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit',		'limit',		$mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( JBCOMNAME.'limitstart',	'limitstart',	0, 'int' );
//    	$filter_location    = $mainframe->getUserStateFromRequest( JBCOMNAME .".japermission.filter_location",   'filter_location',        '',    'cmd' );
//        $filter_state       = $mainframe->getUserStateFromRequest( JBCOMNAME .".japermission.filter_state",      'filter_state',        '',    'word' );
//        $filter_catid       = $mainframe->getUserStateFromRequest( JBCOMNAME.".japermission.filter_catid",       'filter_catid',        '',    'string' );
        $filter_order		= $mainframe->getUserStateFromRequest( JBCOMNAME .".japermission.filter_order",		'filter_order',		'id',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( JBCOMNAME .".japermission.filter_order_Dir",	'filter_order_Dir',	'DESC',			'word' );
        $search				= $mainframe->getUserStateFromRequest( JBCOMNAME .".japermission.search",			'search',			'',				'string' );
		$search				= JString::strtolower( $search );
		
		$where = null;

		if($search){
			$where[] = " (u.name LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false )." or u.username LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false )." or u.email LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false ).")";			
		}
		if ( $filter_state == 'P' ) {
				$where[] = 'u.block=1';
		} else if ($filter_state == 'U' ) {
			 $where[] = 'u.block=0';
		}		
		
//		if($usertype!=="0"&&$usertype!=null){
//			$where[]=" u.usertype='".$usertype."'";
//		}
//		else
//		{
//			$strusertypes = array();
//			
//			if($group){
//				foreach ($group as $t=>$g){
//					$strusertypes[] = "u.usertype='$t'";
//				}
//			}
//			if($strusertypes) $where[]=" (".implode(' or ', $strusertypes). ")";
//		}
       
        // just in case filter_order get's messed up
		if ($filter_order) {
			$orderby = ' ORDER BY '.$filter_order .' '. $filter_order_Dir;
		} else {
			$orderby = ' ORDER BY u.id DESC';
		}
        $orderby = ' ORDER BY u.id ';
        
        if($where)  $where = "\n WHERE ". implode(' and ', $where);
       
        $query = "SELECT u.*,us.*".
        		"\n FROM #__users as u LEFT JOIN #__ja_permissions as us ON us.user_id=u.id ".
        		$where.
        		$orderby;
		 
        $db = &JFactory::getDBO();
		$db->setQuery($query);	//print_r($db->getQuery($query));exit;
		$items_temp = $db->loadObjectList();
		$items = array();
		foreach ($items_temp as $item) {
			if ($usergroup=='admin')
			{
				
				if (($usertype!='0')&&($usertype!=''))
				{
					if ($item->usertype==$usertype)
						$items[] = $item;
				}
				else 
				{
					if (($item->usertype=='Administrator')||($item->usertype=='Super Administrator')||($item->usertype=='Magager'))
						$items[] = $item;
				}
			}
			else 
			{
				if (($item->usertype!='Administrator')&&($item->usertype!='Super Administrator'))
					if ($usertype!='')
					{
						if ((getUserType($item->id)==$usertype))
							$items[] = $item;
					}
					else 
						$items[] = $item;
			}
		}
		$total = count( $items );

		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $total, $limitstart, $limit );
		
		$list = array();
		// slice out elements based on limits
		if($items)
		$list = array_slice( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		
		return $list;
    }
    
    /**
	* Get page navigator object
	* @return 
	*/
	function &getPagination(){
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}
	
	// save a permission when edit or new.
	function store()	{
		global $jbconfig;
		
		$db	=	JFactory::getDBO();
		
		$post		= JRequest::get( 'post' );
		
		$cbs		=	$post['cb'];
		$userid		=	$post['cid'];
		$user_permission	=	$post['user_per'];
		$user_permission_new	=	0;
		$usergroup = $post['usergroup'];
				
		if($cbs){
			foreach ($cbs as $c){
				$user_permission_new = (intval($user_permission_new)|$c);
			}
		}
		
		if( $user_permission_new!=$user_permission ){		
			$query = "SELECT * FROM #__ja_permissions WHERE user_id=".(int)$userid;				
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if($result){
				$query = "UPDATE #__ja_permissions SET permission='$user_permission_new' WHERE user_id='$userid'";
			}
			else{
				$query = "INSERT INTO #__ja_permissions (permission, user_id) Values('$user_permission_new', '$userid')";	
			}
			$db->setQuery($query);
			if($db->query())
			{
				$msg = JText::_('SUCCESSFULLY UPDATE PERMISSIONS');
			}
			else 
			{
				$msg = JText::_('FAILURE TO UPDATE PERMISSIONS');
			}
		}
		else 
		{
			$msg = JText::_('THIS PERMISSIONS ARE ALREADY AVAILABLE EXITS');
		}
			
		return $msg;
	}
	
	// save a permission when edit or new.
	function store_group()	{
		global $jbconfig;
		
		$db	=	JFactory::getDBO();
		
		$post		= JRequest::get( 'post' );
		
		$cbs		=	$post['cb'];
		$group_permission	=	$post['group_per'];
		$group_permission_new	=	0;
		$usertype = $post['usertype'];
		$group = str_replace(' ', '_', $usertype.'_permission');
			
		if($cbs){
			foreach ($cbs as $c){
				$group_permission_new = (intval($group_permission_new)|$c);
			}
		}
		
		$group_permission_old = $jbconfig['group_permission']->get($group, '0');
		if( $group_permission_new==$group_permission_old  &&  $group_permission_old>0){
			$msg=JText::_('SUCCESSFULLY UPDATE PERMISSIONS FOR GUEST USER');
		}
		else {				
			$paramsField = $jbconfig['group_permission']->_registry['_default']['data'];
			$params = new JParameter('');
			$data = array();
			$check = false;
			foreach ($paramsField as $k => $v){
				if( $k==$group ){
					$v = $group_permission_new;
					$check = true;
				}
				$params->set($k, $v);
				
			}
			if (!$check) {
				$params->set($group, $group_permission_new);
			}
			
			$data = $params->toString();
			
			$query	=	"UPDATE #__ja_config SET data='$data' WHERE tab='group_permission'";
			$db->setQuery($query);
			if($db->query())
				$msg=JText::_('SUCCESSFULLY UPDATE PERMISSIONS FOR GUEST USER');
			else 
				$msg=JText::_('FAILURE TO UPDATE PERMISSIONS FOR GUEST USER');				
		}
						
		return $msg;
	}
	function initial_per($user_id=0,$usertype='')
	{
		$db = & JFactory::getDBO();
		if ($user_id!=0)
			$user = JFactory::getUser($user_id);
		else 
			$user = JFactory::getUser();
		if ($usertype=='')
			$usertype = getCurrentUserType($user->id);
		if ($usertype=='Job Seeker User')
			$query = 'SELECT * FROM #__ja_subscriptions WHERE subs_type="jobseeker" and isdefault=1 and published=1';
		else 
			$query = 'SELECT * FROM #__ja_subscriptions WHERE subs_type="employer" and isdefault=1 and published=1';
		$db->setQuery($query);
		$initial_per = $db->loadObjectList();
		$initial_per = $initial_per[0]->permission;
		//Check existing permission
		$query = 'SELECT * FROM #__ja_permissions WHERE user_id='.(int)$user->id;
		$db->setQuery($query);
		$item = $db->loadObjectList();
		if (!$item)	{
			$query = 'INSERT INTO #__ja_permissions VALUES ('.$user->id.','.$initial_per.')';
		}
		else 
		{
			$query = 'UPDATE #__ja_permissions SET permission='.$initial_per.' WHERE user_id='.$user->id;
		}
		$db->setQuery($query);
		$db->query();
		
		//Check existing employer
		$query = 'SELECT * FROM #__ja_employers WHERE user_id='.(int)$user->id;
		$db->setQuery($query);
		$item = $db->loadObjectList();
		if (!$item)	{
			$query = 'INSERT INTO #__ja_employers (user_id) VALUES ('.$user->id.')';
			$db->setQuery($query);
			$db->query();
		}		
		
	}
	
	
}